package com.ruoyi.yipaiju.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.enums.dict.HouseCategory;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.yipaiju.domain.AccessLog;
import com.ruoyi.yipaiju.domain.DiscountHouse;
import com.ruoyi.yipaiju.domain.ForeclosedHouse;
import com.ruoyi.yipaiju.service.IAccessLogService;
import com.ruoyi.yipaiju.service.IDiscountHouseService;
import com.ruoyi.yipaiju.service.IForeclosedHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/access")
public class AccessController extends BaseController {

    @Autowired
    private IAccessLogService accessLogService;
    @Autowired
    private IForeclosedHouseService foreclosedHouseService;
    @Autowired
    private IDiscountHouseService discountHouseService;

    /**
     * 房源详情查询日志
     * @param accessLog
     * @return
     */
    @PostMapping("/log")
    public ApiResult log(HttpServletRequest request, @RequestBody AccessLog accessLog) {
        accessLog.setClientIp(IpUtils.getIpAddr(request));
        accessLog.setUserId(SecurityUtils.getUserId());
        accessLogService.insertAccessLog(accessLog);
        // 浏览数+1
        if (HouseCategory.FORECLOSED.getValue().toString().equals(accessLog.getHouseCategory())){
            foreclosedHouseService.updateForeclosedHouse(Builder.of(ForeclosedHouse::new)
                    .with(ForeclosedHouse::setBrowseCount1, 1)
                    .with(ForeclosedHouse::setId, accessLog.getHouseId())
                    .build());
        }else if (HouseCategory.DISCOUNT.getValue().toString().equals(accessLog.getHouseCategory())){
            discountHouseService.updateDiscountHouse(Builder.of(DiscountHouse::new)
                    .with(DiscountHouse::setBrowseCount1, 1)
                    .with(DiscountHouse::setId, accessLog.getHouseId())
                    .build());
        }
        return ApiResult.success();
    }
}
